/**
 *  JSimProd - Java simulation code for production processes
 *  Copyleft Jorge Mira Yagüe <jorge.mira.yague@gmail.com>
 *  Universidad de Alicante 2009
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package lib.model;

import lib.xml.XMLizable;
import lib.exceptions.InvalidBatchsValueException;
import lib.exceptions.UnfulfillableRestrictionsException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import lib.model.queue.*;
import lib.plan.Item;

/**
 *
 * @author Jorge Mira Yagüe
 */
public class BufferedStation extends Station implements XMLizable {

    private List<Restriction> restrictions;
    private Restriction stationRestriction;
    private List<Item> itemList;

    public BufferedStation() {
        restrictions = null;
        stationRestriction = null;
        itemList = null;
    }

    public BufferedStation(String name,
            QueueType queueType,
            int minItems,
            int maxItems)
            throws InvalidBatchsValueException {
        super(name, queueType);
        restrictions = null;
        stationRestriction = new Restriction(null, minItems, maxItems);
        itemList = null;
    }

    public int getMinBatch() {
        return stationRestriction.getMinBatch();
    }

    public int getMaxBatch() {
        return stationRestriction.getMaxBatch();
    }

    public void setRestrictions(List<Restriction> restrictions)
            throws UnfulfillableRestrictionsException {
        int minBatchs = 0;
        int maxBatchs = 0;
        /**
         * Repeated itemCategories
         */
        for (Restriction r1 : restrictions) {
            for (Restriction r2 : restrictions) {
                if (r1 != r2 && r1.getItemCategory().equals(r2.getItemCategory())) {
                    throw new UnfulfillableRestrictionsException();
                }
            }
            minBatchs += r1.getMinBatch();
            maxBatchs += r1.getMaxBatch();
        }
        /**
         * The minimum batch number of all restrictions is greater than the
         * station maximum batch
         */
        if (minBatchs > stationRestriction.getMaxBatch()) {
            throw new UnfulfillableRestrictionsException();
        }

        /**
         * The maximum batch number of all restrictions is lesser than the
         * station minimum batch
         */
        if (maxBatchs < stationRestriction.getMinBatch()) {
            throw new UnfulfillableRestrictionsException();
        }

        this.restrictions = restrictions;
    }

    public List<Restriction> getRestrictions() {
        return restrictions;
    }

    @Override
    public Item pollItem() {
        if (itemList == null || itemList.isEmpty()) {
            itemList = fitRestrictions();
            if (itemList == null) {
                return null;
            } else {
                return itemList.remove(0);
            }
        } else {
            return itemList.remove(0);
        }
    }

    private List<Item> fitRestrictions() {
        List<Item> result = new ArrayList<Item>();
        Vector<Item> items = queue.getElements();
        int maxItems;
        int minBatchs[] = new int[restrictions.size()];
        int taken[] = new int[restrictions.size()];
        boolean takeIt[] = new boolean[items.size()];
        int itemCount = 0;
        int removeds;
        boolean fits = true;

        if (restrictions == null) {
            if (items.size() < stationRestriction.getMinBatch()) {
                result = null;
            } else {
                maxItems = items.size() < stationRestriction.getMaxBatch()
                        ? items.size() : stationRestriction.getMaxBatch();
                for (int i = 0; i < maxItems; i++) {
                    result.add(queue.poll());
                }
            }
        } else {
            for (int i = 0; i < restrictions.size(); i++) {
                minBatchs[i] = restrictions.get(i).getMinBatch();
                itemCount += minBatchs[i];
                taken[i] = 0;
            }
            itemCount = stationRestriction.getMaxBatch() - itemCount;
            for (int i = 0; i < items.size(); i++) {
                for (int j = 0; j < restrictions.size(); j++) {
                    if (restrictions.get(j).getItemCategory().equals(
                            items.get(i).getCategory())) {
                        if (minBatchs[j] > 0) {
                            minBatchs[j]--;
                            taken[j]++;
                            takeIt[i] = true;
                        } else if (itemCount > 0 &&
                                taken[j] < restrictions.get(j).getMaxBatch()) {
                            itemCount--;
                            taken[j]++;
                            takeIt[i] = true;
                        } else {
                            takeIt[i] = false;
                        }
                        break;
                    }
                }
            }
            for (int i = 0; i < restrictions.size(); i++) {
                if (minBatchs[i] != 0) {
                    fits = false;
                    break;
                }
            }
            if (fits) {
                removeds = 0;
                for (int i = 0; i - removeds < items.size(); i++) {
                    if (takeIt[i]) {
                        result.add(items.remove(i - removeds));
                        removeds++;
                    }
                }
                queue.setSize(queue.size() - removeds);
            } else {
                result = null;
            }
        }
        return result;
    }

    @Override
    public String toXML() {
        String result = "<BufferedStation ";
        result += "name=\"" + name + "\" ";
        result += "queueType=\"" + queueType + "\" ";
        result += "minBatch=\"" + stationRestriction.getMinBatch() + "\" ";
        result += "maxBatch=\"" + stationRestriction.getMaxBatch() + "\" ";
        result += ">\n";
        result += "<repairs>\n" + repairs.toXML() + "</repairs>\n";
        result += "<shifts>\n" + shifts.toXML() + "</shifts>\n";
        for (String task : tasks) {
            result += "<taskName name=\"" + task + "\" />\n";
        }
        for (String connexion : connexions) {
            result += "<connexionName name=\"" + connexion + "\"/>\n";
        }
        if (restrictions != null) {
            result += "<restrictions>\n";
            for (Restriction restriction : restrictions) {
                result += restriction.toXML();
            }
            result += "</restrictions>\n";
        }
        result += "</BufferedStation>\n";
        return result;
    }
}
